package com.oceansoft.mobile.econsole.modules.complaint.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Strings;
import com.oceansoft.mobile.econsole.cache.redis.CacheBaseService;
import com.oceansoft.mobile.econsole.common.util.FileUtils;
import com.oceansoft.mobile.econsole.modules.api.entity.DealDept;
import com.oceansoft.mobile.econsole.modules.base.entity.ApiPager;
import com.oceansoft.mobile.econsole.modules.base.entity.Query;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.complaint.entity.*;
import com.oceansoft.mobile.econsole.modules.complaint.persistence.IComplaintMapper;
import com.oceansoft.mobile.econsole.modules.complaint.service.IComplaintService;
import com.oceansoft.mobile.econsole.modules.weixin.persistence.WeixinQueryMapper;
import com.oceansoft.mobile.econsole.modules.weixin.service.WeixinQueryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/2/23.
 */
@Service
public class ComplaintServiceImpl extends CacheBaseService implements IComplaintService {

    @Resource
    private IComplaintMapper complaintMapper;
    @Resource
    private WeixinQueryMapper weixinQueryMapper;
    @Resource
    private WeixinQueryService weixinQueryService;
    @Override
    @Transactional
    public Result saveComplaintAttach(MultipartHttpServletRequest request) throws IOException {
        long start = System.currentTimeMillis();
        String guid = request.getParameter("guid");
        if (StringUtils.isBlank(guid)) {
            // modify by shaom 20160805
            // 由于数据库字段有非空修改，这边先不保存了
            guid = UUID.randomUUID().toString();
        }

        String url = configInfo.getFileServerHost();
        int port = Integer.parseInt(configInfo.getFileServerPort());
        String username = configInfo.getFileServerUsername();
        String password = configInfo.getFileServerPassword();

        List<MultipartFile> list = request.getFiles("photos");
        for (MultipartFile mp : list) {
            if (mp.getSize() > 0) {
                ComplaintAttach attach = new ComplaintAttach();
                attach.setGuid(UUID.randomUUID().toString().replaceAll("-", ""));
                attach.setfGuid(guid);
//                attach.setAttach(mp.getBytes()); //数据库存二进制流

                String time = new SimpleDateFormat("yyyyMM").format(new Date());
                String extName = FileUtils.getExtName(mp.getOriginalFilename());
                String newFileName = String.format("%s_%s%s", attach.getGuid(), time, extName);
//                String bizParentDir = configInfo.getBizDayDirRelPath(userGuid, configInfo.getComplaintDir());
                InputStream in = mp.getInputStream();


                if ("".equals(FileUtils.getExtName(newFileName))) {
                    FileUtils.uploadFile(url, port, username, password, "", newFileName + ".jpg", in);//"DATA/" + time
                    attach.setAttachPath(String.format("%s\\%s", time, newFileName) + ".jpg");
                } else {
                    FileUtils.uploadFile(url, port, username, password,"", newFileName, in);//"DATA/" + time
                    attach.setAttachPath(String.format("%s\\%s", time, newFileName));
                }
                attach.setfSize(mp.getSize());
                attach.setAttachType("0");//图片
                attach.setSaveType(1);//
                attach.setfName(mp.getOriginalFilename());//文件名
                //存储文件至文件系统
//                mp.transferTo(FileUtils.createFile(new File(String.format("%s/%s", configInfo.getFileUploadRootPath(), bizParentDir)), newFileName));
                complaintMapper.saveComplaintAttach(attach);
            }

        }

        MultipartFile video = request.getFile("video");
        if (null != video && 0 < video.getSize()) {
            ComplaintAttach attach = new ComplaintAttach();
            attach.setGuid(UUID.randomUUID().toString().replaceAll("-", ""));
            attach.setfGuid(guid);
//            attach.setAttach(video.getBytes()); //数据库存二进制流

            String time = new SimpleDateFormat("yyyyMM").format(new Date());

            String extName = FileUtils.getExtName(video.getOriginalFilename());
            String newFileName = String.format("%s_%s%s", attach.getGuid(), time, extName);
//                String bizParentDir = configInfo.getBizDayDirRelPath(userGuid, configInfo.getComplaintDir());
            InputStream in = video.getInputStream();
            long up=System.currentTimeMillis();
            System.out.println( "+++++++++++++++++++++++++++++++++++++++开始上传时间之前消耗时间："+(up-start)+"+++++++++++++++++++++++++++++++++++++++");
            if ("".equals(FileUtils.getExtName(newFileName))) {
                FileUtils.uploadFile(url, port, username, password, "", newFileName + ".mp4", in);
                attach.setAttachPath(String.format("%s\\%s", time, newFileName) + ".mp4");
            } else {
                FileUtils.uploadFile(url, port, username, password, "", newFileName, in);
                attach.setAttachPath(String.format("%s\\%s", time, newFileName));
            }
            System.out.println( "+++++++++++++++++++++++++++++++++++++++上传视频时间："+(System.currentTimeMillis()-up)+"+++++++++++++++++++++++++++++++++++++++");
            attach.setfName(video.getOriginalFilename());//文件名
            attach.setfSize(video.getSize());
            attach.setAttachType("1");//视频
            attach.setSaveType(1);//
            //存储文件至文件系统
//            video.transferTo(FileUtils.createFile(new File(String.format("%s/%s", configInfo.getFileUploadRootPath(), bizParentDir)), newFileName));
            complaintMapper.saveComplaintAttach(attach);
        }
        return new Result(Result.SUCC, guid, "图片/视频上传成功");
    }

    @Override
    @Transactional
    public Result addComplaintInfo(ComplaintReport complaintReport) {

        String lsh = complaintMapper.getLsh();
        String bm = complaintReport.getPt() + "220000" + new SimpleDateFormat("yyMMdd").format(new Date()) + "30" + lsh;
        complaintReport.setPt(bm);//举报编码
//        complaintReport.setCrType(1);//类型
        complaintReport.setDeptId("230600000000");//部门ID。
        complaintReport.setDeptName("大庆市公安局");//部门姓名
        complaintReport.setCreateDate(new Date());//app端线索举报
        int rt = 0;
        // modify by shaom 20160805
        // 由于数据库字段有非空修改，保存图片时不会保存，这边统一处理
        if (Strings.isNullOrEmpty(complaintReport.getGuid())) {
            complaintReport.setGuid(UUID.randomUUID().toString());
        }
        rt = complaintMapper.saveComplaintInfo(complaintReport);

        if (rt > 0) {
            return new Result(Result.SUCC, "线索举报上传成功");
        }
        return new Result(Result.FAILURE, "线索举报上传失败");
    }

    @Override
    @Transactional
    public Result addComplaintCenter(CompltProInfo compltProInfo, CompltCenter compltCenter) {
        /*String projectBillId = complaintMapper.createProjectBillId();
        if(StringUtils.isNotBlank(projectBillId)){
            compltProInfo.setProjectBillId(projectBillId);
            complaintMapper.saveCompltProInfo(compltProInfo);
        }*/
        complaintMapper.saveCompltProInfo(compltProInfo);

        complaintMapper.saveCompltCenter(compltCenter);

        return new Result(Result.SUCC, "感谢您对公安机关反腐倡廉建设的关心和支持，我们会在两个工作日内给您答复受理情况，请到个人中心-我的投诉查看回复。");
    }

    @Override
    public ApiPager loadComplaintByPage(Query query) {
        PageHelper.startPage(query.getPageNum(), query.getNumPerPage(), true);
        Page<CompltCenter> page = (Page<CompltCenter>) complaintMapper.loadComplaintByCondition(query);
        ApiPager<CompltCenter> apiPager = new ApiPager<CompltCenter>(query.getNumPerPage(), query.getPageNum(), page.getTotal(), page.getResult());
        return apiPager;
    }

    @Override
    public Result loadComplaintReply(String projectGuid) {
        CompltCenterReply compltCenterReply = complaintMapper.loadComplaintReplyByCGuid(projectGuid);
        if (null != compltCenterReply) {
            return new Result(Result.SUCC, compltCenterReply, "获取投诉回复信息成功");
        }
        return new Result(Result.FAILURE, "获取投诉回复信息失败");
    }

    @Override
    @Transactional
    public Result loadComplaintDetail(String projectGuid) {
        try {
            CompltProInfo compltProInfo = complaintMapper.loadCompltProInfoByGuid(projectGuid);

            CompltCenter compltCenter = complaintMapper.loadCompltCenterByProjectGuid(projectGuid);

            CompltCenterReply compltCenterReply = complaintMapper.loadComplaintReplyByCGuid(projectGuid);
            compltProInfo.setCompltCenter(compltCenter);
            compltProInfo.setCompltCenterReply(compltCenterReply);

            return new Result(Result.SUCC, compltProInfo, "成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "失败");
        }

    }

    @Override
    public Result loadDealFirstDeptList() {
        String key = "app:complaint:firstdept";
        List<DealDept> list = null;
        if (super.exists(key)) {
            list = (List<DealDept>) super.getObject(key);
            return new Result(Result.SUCC, list);
        }
        list = complaintMapper.loadDealFirstDeptList();
        if (null != list) {
            return new Result(Result.SUCC, list, "获取接受部门一级菜单成功");
        }
        return new Result(Result.FAILURE, "获取失败");
    }

    @Override
    public Result loadDealSecDeptList(String deptId) {
        String key = "app:complaint:secdept";
        List<DealDept> list = null;
        if (super.exists(key)) {
            list = (List<DealDept>) super.getObject(key);
            return new Result(Result.SUCC, list);
        }
        list = complaintMapper.loadDealSecDeptList(deptId);
        if (null != list) {
            return new Result(Result.SUCC, list, "获取接受部门二级菜单成功");
        }
        return new Result(Result.FAILURE, "获取失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveComplain(ComplaintReport complaintReport) throws IOException {
        if (Strings.isNullOrEmpty(complaintReport.getGuid())) {
            complaintReport.setGuid(UUID.randomUUID().toString());
        }
        String lsh = complaintMapper.getLsh();
        String bm = "SS"+ "220000" + new SimpleDateFormat("yyMMdd").format(new Date()) + "30" + lsh;
        complaintReport.setPt(bm);//举报编码
//        String lsh = weixinQueryService.getSlbh(Constant.WXJB_XSJB);
//        String bm = "XB" + "220000" + new SimpleDateFormat("yyMMdd").format(new Date()) + "30" + lsh;
//        complaintReport.setPt(bm);//举报编码
        complaintReport.setCreateDate(new Date());//服务器时间 微信端app端随手拍
        try{
            weixinQueryMapper.savewxjbxsjb(complaintReport);
            return new Result(Result.SUCC, "随手拍上传成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(Result.FAILURE,"随手拍上传失败");
        }

    }
}
